package com.carleasoft.mps.adu.business.user.service.impl;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.carleasoft.mps.adu.business.user.bean.entity.AuthorityUserDept;
import com.carleasoft.mps.adu.business.user.bean.entity.AuthorityUserEntity;
import com.carleasoft.mps.adu.business.user.bean.po.AuthorityAdminPo;
import com.carleasoft.mps.adu.business.user.bean.vo.DeptUserTreeVo;
import com.carleasoft.mps.adu.business.user.bean.vo.DeptUserVo;
import com.carleasoft.mps.adu.business.user.dao.AuthorityUserDeptDao;
import com.carleasoft.mps.adu.business.user.service.AuthorityUserAdminService;
import com.carleasoft.mps.adu.business.user.service.AuthorityUserDeptService;
import com.carleasoft.mps.adu.business.user.service.AuthorityUserService;
import com.carleasoft.mps.core.exceptions.BusinessException;
import com.carleasoft.mps.core.user.*;
import com.carleasoft.mps.core.utils.ConvertUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

import static com.carleasoft.mps.adu.common.constants.BusinessErrorEnum.DUPLICATE_USER_ACCOUNT;

/**
 * @author taoyujing
 * @date 2021-11-22 15:07
 * @project services
 */
@Service
public class AuthorityUserAdminServiceImpl implements AuthorityUserAdminService {

    @Autowired
    private AuthorityUserService authorityUserService;
    @Autowired
    private AuthorityUserDeptService authorityUserDeptService;
    @Autowired
    private AuthorityUserDeptDao authorityUserDeptDao;

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public AuthorityUserEntity addOrgAdmin(AuthorityAdminPo authorityAdminPo) {
        AuthorityUserEntity userEntity =null;
        //校验用户账号的是否重复
       if (Objects.nonNull(authorityAdminPo.getUserCode())) {
            //用户账号重复
            AuthorityUserEntity one = this.authorityUserService.getOne(Wrappers.<AuthorityUserEntity>lambdaQuery().eq(AuthorityUserEntity::getUserAccount,authorityAdminPo.getUserAccount()));
            if(Objects.nonNull(one)&&!userEntity.getUserCode().equals(authorityAdminPo.getUserCode())){
                throw new BusinessException(DUPLICATE_USER_ACCOUNT);
            }
            userEntity = this.authorityUserService.getOne(Wrappers.<AuthorityUserEntity>lambdaQuery().eq(AuthorityUserEntity::getUserCode,authorityAdminPo.getUserCode()));
            userEntity.setUserAccount(authorityAdminPo.getUserAccount());
            userEntity.setUserName(authorityAdminPo.getUserName());
            userEntity.setUserStatus(Constants.ENABLE);
            authorityUserService.saveOrUpdate(userEntity);
        }else {
           AuthorityUserEntity one = this.authorityUserService.getOne(Wrappers.<AuthorityUserEntity>lambdaQuery().eq(AuthorityUserEntity::getUserAccount,authorityAdminPo.getUserAccount()));
           if(Objects.nonNull(one)){
               throw new BusinessException(DUPLICATE_USER_ACCOUNT);
           }
            userEntity=new AuthorityUserEntity();
            userEntity = ConvertUtils.sourceToTarget(authorityAdminPo, AuthorityUserEntity.class);
            userEntity.setUserCode(IdWorker.getIdStr());
            userEntity.setUserCat(Constants.ORGANIZATION_SUPER_ADMIN);
            userEntity.setUserStatus(Constants.ENABLE);
            AuthorityUserDept authorityUserDept = new AuthorityUserDept();
            authorityUserDept.setUserCode(userEntity.getUserCode());
            authorityUserDept.setDeptCode(authorityAdminPo.getOrganizationCode());
            if (StringUtils.isBlank(authorityUserDept.getDeptCode())){
                UserCacheData user = ThreadUserContext.getCurrentCacheUser();
                for (UserPro userPro : user.getUserPros()) {
                    UserDeptVo userDeptVo = userPro.getUserDeptVoList().get(0);
                    authorityUserDept.setDeptCode(userDeptVo.getDeptCode());
                }
            }
            authorityUserDeptService.save(authorityUserDept);
            authorityUserService.save(userEntity);
        }
        return userEntity;
    }

    @Override
    public List<AuthorityUserEntity> administratorsList(AuthorityAdminPo authorityAdminPo) {
        UserCacheData user = ThreadUserContext.getCurrentCacheUser();
        if(user.getUserCat()==Constants.SUPER_ADMIN) {
            authorityAdminPo.setOrganizationCode(user.getOrgCodeJoin());
            return authorityUserDeptDao.administratorsList(Constants.SYSTEM_ADMIN,authorityAdminPo);
        }
        else if(user.getUserCat()==Constants.ORGANIZATION_SUPER_ADMIN){
            authorityAdminPo.setOrganizationCode(user.getOrgCodeJoin());
            return authorityUserDeptDao.administratorsList(Constants.ORGANIZATION_SUPER_ADMIN,authorityAdminPo);
        }
        else {
            return null;
        }
    }

    @Override
    public List<DeptUserTreeVo> getDeptUserTree() {
        // 获取可选的用户接集合
        List<DeptUserVo> allActiveUser =  authorityUserDeptDao.getAllActiveUser();
        List<DeptUserVo> allActiveDept =  authorityUserDeptDao.getAllActiveDept();

        List<DeptUserVo> needBuildDept = new ArrayList<>();
        List<DeptUserVo> topNode = new ArrayList<>();
        // 获取需要组织的部门树
        for (DeptUserVo deptUserVo : allActiveUser) {
            this.getNeedDept(deptUserVo,needBuildDept,allActiveDept);
            topNode = needBuildDept.stream().filter(t -> t.getParentDeptCode().equals("0")).collect(Collectors.toList());
        }
        List<DeptUserTreeVo> resDeptTree = new ArrayList<>();
        // 创建部门树
        for (DeptUserVo deptUserVo : topNode) {
            DeptUserTreeVo addRes  = new DeptUserTreeVo();
            addRes.setLabel(deptUserVo.getDeptName());
            addRes.setValue(deptUserVo.getDeptCode());
            addRes.setKey(deptUserVo.getDeptCode());
            this.buildDeptTree(addRes,needBuildDept);
            resDeptTree.add(addRes);
        }
        // 修饰给部门树添加 用户
        for (DeptUserVo deptUserVo : allActiveUser) {
            for (DeptUserTreeVo deptUserTreeVo : resDeptTree) {
                this.buildDeptUserTree(deptUserTreeVo,deptUserVo);
            }
        }
        return resDeptTree;
    }
    public void buildDeptTree(DeptUserTreeVo res ,  List<DeptUserVo> allActiveDept) {
        if(StringUtils.isNotBlank(res.getValue())){
            List<DeptUserVo> addChildren = allActiveDept.stream()
                    .filter(t -> t.getParentDeptCode().equals(res.getValue())).collect(Collectors.toList());
            if(addChildren.size()>0){
                List<DeptUserTreeVo> children = new ArrayList<>();
                for (DeptUserVo addChild : addChildren) {
                    DeptUserTreeVo addItem  = new DeptUserTreeVo();
                    addItem.setLabel(addChild.getDeptName());
                    addItem.setValue(addChild.getDeptCode());
                    addItem.setKey(addChild.getDeptCode());
                    this.buildDeptTree(addItem,allActiveDept);
                    children.add(addItem);
                }
                res.setChildren(children);
            }

        }
    }
    public void buildDeptUserTree(DeptUserTreeVo res,DeptUserVo user){
        if(StringUtils.isNotBlank(res.getValue()) && res.getValue().equals(user.getDeptCode())){
            List<DeptUserTreeVo> children = res.getChildren();
            if(null != children){
                DeptUserTreeVo addUser =  new DeptUserTreeVo();
                addUser.setLabel(user.getUserName());
                addUser.setValue(user.getUserCode());
                addUser.setIsUser(1);
                addUser.setKey(user.getDeptCode()+"-"+user.getUserCode());
                children.add(addUser);
            } else {
                children = new ArrayList<>();
                DeptUserTreeVo addUser =  new DeptUserTreeVo();
                addUser.setLabel(user.getUserName());
                addUser.setValue(user.getUserCode());
                addUser.setIsUser(1);
                addUser.setKey(user.getDeptCode()+"-"+user.getUserCode());
                children.add(addUser);
            }
            res.setChildren(children);
        } else {
            List<DeptUserTreeVo> children = res.getChildren();
            if(null != children) {
                for (DeptUserTreeVo child : children) {
                    this.buildDeptUserTree(child,user);
                }
            }
        }
    }
    public void getNeedDept(DeptUserVo deptUserVo, List<DeptUserVo> needBuildDept,List<DeptUserVo> allActiveDept){
        List<DeptUserVo> collect = needBuildDept.stream()
                .filter(t -> t.getDeptCode().equals(deptUserVo.getDeptCode())).collect(Collectors.toList());
        if(collect.size() == 0){
            DeptUserVo add = allActiveDept.stream()
                    .filter(t -> t.getDeptCode().equals(deptUserVo.getDeptCode())).collect(Collectors.toList()).get(0);
            needBuildDept.add(add);
            if(StringUtils.isNotBlank(add.getParentDeptCode()) && !add.getParentDeptCode().equals("0")){
                DeptUserVo parentNode = new DeptUserVo();
                parentNode.setDeptCode(add.getParentDeptCode());
                this.getNeedDept(parentNode,needBuildDept,allActiveDept);
            }
        }
    }
    @Override
    public AuthorityUserEntity addSystemAdmin(AuthorityAdminPo authorityAdminPo) {
        AuthorityUserEntity userEntity=null;
        List<AuthorityUserEntity> userEntitys = this.administratorsList(authorityAdminPo);
        if (userEntitys!=null&&userEntitys.size()==1) {
            //用户账号重复
            userEntity =userEntitys.get(0);
            if(!userEntity.getUserCode().equals(authorityAdminPo.getUserCode())){
                throw new BusinessException(DUPLICATE_USER_ACCOUNT);
            }
            userEntity.setUserAccount(authorityAdminPo.getUserAccount());
            userEntity.setUserName(authorityAdminPo.getUserName());
            userEntity.setRemark(authorityAdminPo.getRemark());
            userEntity.setUserStatus(Constants.ENABLE);
            authorityUserService.saveOrUpdate(userEntity);
        }else {
            userEntity = ConvertUtils.sourceToTarget(authorityAdminPo, AuthorityUserEntity.class);
            userEntity.setUserCode(IdWorker.getIdStr());
            userEntity.setUserStatus(Constants.ENABLE);
            UserCacheData user = ThreadUserContext.getCurrentCacheUser();
            if(user.getUserCat()==Constants.SUPER_ADMIN) {
                userEntity.setUserCat(Constants.SYSTEM_ADMIN);
            }
            else if(user.getUserCat()==Constants.ORGANIZATION_SUPER_ADMIN){
                userEntity.setUserCat(Constants.ORGANIZATION_SYSTEM_ADMIN);
            }
            AuthorityUserDept authorityUserDept = new AuthorityUserDept();
            authorityUserDept.setUserCode(userEntity.getUserCode());
            authorityUserDept.setDeptCode(authorityAdminPo.getDeptCode());
            authorityUserDeptService.save(authorityUserDept);
            authorityUserService.save(userEntity);
        }

        return userEntity;
    }


}
